package com.supermarket.manage.business.member.controller;

import com.supermarket.manage.common.constant.RedisKeyConstant;
import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import com.supermarket.manage.common.dto.member.request.SetDiscountParams;
import com.supermarket.manage.common.utils.BigDecimalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-03-12 19:40
 **/
@RestController
@RequestMapping("/member")
@Api(value = "DiscountController", tags = "会员折扣管理接口")
public class DiscountController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PreAuthorize("hasAnyAuthority('/','/member/manage')")
    @PostMapping("/setDiscount")
    @ApiOperation(value = "设置会员折扣", notes = "参数：discount，buyerId（discount为折扣率，如7.5折则discount为7.5）")
    public ResponseResult<Void> setDiscount(@Validated
                                            @RequestBody SetDiscountParams params) {
        String key = RedisKeyConstant.DISCOUNT_CAT + params.getBuyerId();
        BigDecimal bigDecimal = BigDecimalUtil.format(params.getDiscount(), 2);
        stringRedisTemplate.opsForValue().set(key, bigDecimal.toString());
        if (stringRedisTemplate.hasKey(key)) {
            return new ResponseResult<>(CodeStatus.OK, "设置成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "设置失败");
    }

    @PreAuthorize("hasAuthority('/logined')")
    @GetMapping("/getDiscount/{buyerId}")
    @ApiOperation(value = "获取会员折扣", notes = "获取会员折扣")
    public ResponseResult<BigDecimal> getDiscount(@NotBlank(message = "客户id不能为空")
                                                  @PathVariable String buyerId) {
        String str = stringRedisTemplate.opsForValue().get(RedisKeyConstant.DISCOUNT_CAT + buyerId);
        if (StringUtils.isNotBlank(str)) {
            return new ResponseResult<>(CodeStatus.OK, "查询成功", new BigDecimal(str));
        }
        return new ResponseResult<>(CodeStatus.OK, "查询成功", BigDecimalUtil.getNumber(new BigDecimal(10), 2));
    }

}
